package com.yyfax.pay.quartz.adapter.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.google.common.collect.ImmutableMap;
import com.yyfax.framework.common.Log;
import com.yyfax.pay.common.annotation.DepositQueryTaskType;
import com.yyfax.pay.common.enums.FuiouBusiTypeEnum;
import com.yyfax.pay.common.exception.PayException;
import com.yyfax.pay.depository.domain.FuiouQueryTask;
import com.yyfax.pay.depository.service.inner.TradeQueryService;
import com.yyfax.pay.depository.to.TradeQueryReq;
import com.yyfax.pay.quartz.adapter.DepositQueryHandlerAdapter;
import com.yyfax.pay.quartz.model.vo.TaskResultVO;
import com.yyfax.pay.third.facade.fuioudeposit.FuiouDepositService;
import com.yyfax.pay.vo.depository.FuiouTradeTypeEnum;

/**
 * 富友存管交易查询
 * 
 * @author heizq
 * @date 2017-09-12 14:30:49
 * @since v1.0.0
 */
@Service
@DepositQueryTaskType(FuiouBusiTypeEnum.TRADE_QUERY)
public class FuiouTradeQueryHandler implements DepositQueryHandlerAdapter {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private TradeQueryService tradeQueryService;

	@Resource
	private FuiouDepositService fuiouDepositService;

	/** 构建查询类型和业务类型的关系 */
	private ImmutableMap<FuiouBusiTypeEnum, FuiouTradeTypeEnum> map = ImmutableMap.<FuiouBusiTypeEnum, FuiouTradeTypeEnum> builder()
			.put(FuiouBusiTypeEnum.FROZEN, FuiouTradeTypeEnum.FROZEN).put(FuiouBusiTypeEnum.UNFROZEN, FuiouTradeTypeEnum.UNFROZEN)
			.put(FuiouBusiTypeEnum.FROZEN_TO_FRONZEN, FuiouTradeTypeEnum.FROZEN_TO_FROZEN)
			.put(FuiouBusiTypeEnum.TRANSFER_MERCHANT_USER, FuiouTradeTypeEnum.TRANSFER)
			.put(FuiouBusiTypeEnum.TRANSFER_USER_USER, FuiouTradeTypeEnum.APPROPRIATE)
			.put(FuiouBusiTypeEnum.TRANSFER_FROZEN, FuiouTradeTypeEnum.TRANSFER_FROZEN)
			.put(FuiouBusiTypeEnum.APPROPRIATE_FROZEN, FuiouTradeTypeEnum.APPROPRIATE_FROZEN).build();

	@Override
	public TaskResultVO handle(FuiouQueryTask task) throws Throwable {
		final String op = "FuiouTradeQueryHandler.handle";
		logger.info(Log.op(op).msg("【富友存管】交易查询开始！").kv("busiId", task.getBusiId()).toString());
		TradeQueryReq req = new TradeQueryReq();
		FuiouTradeTypeEnum tradeType = getTradeType(task.getBusiId());
		req.setTradeType(tradeType);
		req.setSearilNo(task.getBusiId());

		boolean queryResult = tradeQueryService.tradeQuery(req, task.getMerchantCode());
		return new TaskResultVO(queryResult);
	}

	/**
	 * 根据业务订单获取交易类型
	 * 
	 * @author heizq
	 * @date 2017-09-28 16:14:52
	 * @since v1.0.0
	 * @param busiId
	 * @return
	 */
	private FuiouTradeTypeEnum getTradeType(String busiId) {
		FuiouBusiTypeEnum type = FuiouBusiTypeEnum.parse(busiId.substring(2, 4));

		FuiouTradeTypeEnum fuiouTradeTypeEnum = map.get(type);
		if (fuiouTradeTypeEnum == null) {
			throw new PayException("不支持的查询类型");
		}
		return fuiouTradeTypeEnum;
	}
}
